package com.yitiao.simple.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        String port = ctx.channel().remoteAddress().toString().split("1:")[1];
        System.out.println("receive message from client[" + port + "]" + msg.text());

        channelGroup.forEach(ch->{
            if (ch!=ctx.channel()){
                String clientPort = ch.remoteAddress().toString().split("1:")[1];
                ch.writeAndFlush(new TextWebSocketFrame("\uD83D\uDCF1client[" + port + "] " + msg.text()));
            }else {
                ch.writeAndFlush(new TextWebSocketFrame("\uD83D\uDC64client[" + port + "] " + msg.text()));
            }
        });
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        String port = ctx.channel().remoteAddress().toString().split("1:")[1];
        System.out.println("client[" + port + "] online...");
        channelGroup.add(ctx.channel());
        ctx.channel().writeAndFlush(new TextWebSocketFrame("port:"+port));
//        System.out.println("asLongText:" + ctx.channel().id().asLongText());
//        System.out.println("asShortText:" + ctx.channel().id().asShortText());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        String port = ctx.channel().remoteAddress().toString().split(":")[1];
        System.out.println("client[" + port + "] offline...");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
